package com.demo.juc.locks;


import java.util.concurrent.locks.ReentrantLock;

/**
 * new ReentrantLock(); 默认非公平， 更好的避免CPU切换的开销，提高吞吐量
 * new ReentrantLock(true);  公平锁
 *
 */
public class UnsafeLock {

    private Integer number = 100;

    //ReentrantLock lock = new ReentrantLock();
    ReentrantLock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println("线程：" + Thread.currentThread().getName() + "卖出第：" + (number--) + "张，还剩：" + number + "张");
            }
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        UnsafeLock ticket = new UnsafeLock();
        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 55; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}
